<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="130px"
    >
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo地址" prop="logo">
        <!-- <el-input v-model="dataForm.logo" placeholder="品牌logo地址"></el-input> -->
        <el-upload
          action="http://tc-guli-file.oss-cn-beijing.aliyuncs.com"
          list-type="picture-card"
          :data="dataObj"
          :multiple="false"
          :before-upload="beforeUpload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-error="handleError"
          :on-success="handleUploadSuccess"
          :fileList="fileList"
          :before-remove="beforeRemove"
          :class="{hide: dataForm.logo}">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>
      <el-form-item label="显示状态" prop="showStatus">
        <el-switch
          v-model="dataForm.showStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input
          v-model="dataForm.firstLetter"
          placeholder="检索首字母"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getUUID } from '@/utils'
export default {
  data () {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      visible: false,
      dataForm: {
        brandId: 0,
        name: '',
        logo: '',
        descript: '',
        showStatus: '',
        firstLetter: '',
        sort: ''
      },
      dataRule: {
        name: [{ required: true, message: '品牌名不能为空', trigger: 'blur' }],
        logo: [
          { required: true, message: '品牌logo地址不能为空', trigger: 'blur' }
        ],
        descript: [
          { required: true, message: '介绍不能为空', trigger: 'blur' }
        ],
        showStatus: [
          {
            required: true,
            message: '显示状态[0-不显示；1-显示]不能为空',
            trigger: 'blur'
          }
        ],
        firstLetter: [
          { required: true, message: '检索首字母不能为空', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
      },
      dataObj: {}
    }
  },
  computed: {
    hiddenUpload () {
      console.log(this.dataForm.logo)
      if (this.dataForm.logo) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    handleUploadSuccess (res, file, fileList) {
      console.log('上传成功...')
      this.fileList.pop()
      this.fileList.push({
        name: file.name,
        url: this.dataObj.host + '/' + this.dataObj.key
      })
      this.dataForm.logo = this.fileList[0].url
    },
    beforeUpload (file) {
      console.log(file)
      let _this = this
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/third-party/oss/policy'),
          method: 'get',
          params: this.$http.adornParams({})
        })
          .then(({ data }) => {
            console.log('响应的数据', data)
            _this.dataObj.policy = data.data.policy
            _this.dataObj.signature = data.data.signature
            _this.dataObj.ossaccessKeyId = data.data.accessid
            _this.dataObj.key = data.data.dir + getUUID() + '_' + file.name
            _this.dataObj.dir = data.data.dir
            _this.dataObj.host = data.data.host
            console.log(_this.dataObj.policy)
            resolve(true)
          })
          .catch(err => {
            console.log(err)
            this.$message({ type: 'error', message: '上传失败,后端签名获取失败' })
            reject(new Error(err))
          })
      })
    },
    handleRemove (file, fileList) {
      this.dataForm.logo = ''
      console.log('handleRemove', file, fileList)
    },
    handlePreview (file) {
      console.log('preview:', file.url)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
      console.log('handlePreview', file)
    },
    handleExceed (files, fileList) {
      console.log('handleExceed', files, fileList)
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove (file, fileList) {
      console.log('beforeRemove', file, fileList)
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleError (err, file, fileList) {
      console.log('handleError', err, file, fileList)
    },
    init (id) {
      this.dataForm.brandId = id || 0
      this.fileList = []
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.brandId) {
          this.$http({
            url: this.$http.adornUrl(
              `/product/brand/info/${this.dataForm.brandId}`
            ),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.brand.name
              this.dataForm.logo = data.brand.logo
              this.dataForm.descript = data.brand.descript
              this.dataForm.showStatus = data.brand.showStatus
              this.dataForm.firstLetter = data.brand.firstLetter
              this.dataForm.sort = data.brand.sort
              this.fileList = []
              this.fileList.push({
                name: data.brand.logo.substring(
                  data.brand.logo.lastIndexOf('/') + 1
                ),
                url: data.brand.logo
              })
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/product/brand/${!this.dataForm.brandId ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.$http.adornData({
              brandId: this.dataForm.brandId || undefined,
              name: this.dataForm.name,
              logo: this.dataForm.logo,
              descript: this.dataForm.descript,
              showStatus: this.dataForm.showStatus,
              firstLetter: this.dataForm.firstLetter,
              sort: this.dataForm.sort
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
.hide .el-upload--picture-card {
    display: none;
}
</style>
